﻿using Domain;
using Domain.Entity;
using Domain.Repository;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EFCore.Repositorys
{
    public class UserRepository : IUserRepository
    {
        private readonly MyDbContext myDbContext;

        public UserRepository(MyDbContext myDbContext)
        {
            this.myDbContext = myDbContext;
        }

        public async Task<List<User>> GetAllUsers()
        {
            return await myDbContext.User.ToListAsync();
        }

        public async Task<User> GetUser(User user)
        {
            User user1=await myDbContext.User.Where(e=>e.UName==user.UName&&e.UPassWord==user.UPassWord).FirstOrDefaultAsync();
            return user1;
        }

		public UserFenYe DataUser(int page, int pageSize)
		{
			var query = myDbContext.User.AsQueryable();
			int totalRecords = query.Count();
			var User = query.Skip((page - 1) * pageSize).Take(pageSize).ToList();
			return new UserFenYe
			{
				totalRecords = totalRecords,
				user = User
			};
		}

		public async Task<bool> AddUser(User user)
		{
			myDbContext.User.Add(user);
			return await myDbContext.SaveChangesAsync() > 0;
		}

		public async Task<bool> UpDateUser(User user)
		{
			myDbContext.User.Update(user);
			return await myDbContext.SaveChangesAsync() > 0;
		}

		public async Task<bool> DeleteUser(int uid)
		{
			User user = new User
			{
				UId = uid
			};
			myDbContext.User.Remove(user);
			return await myDbContext.SaveChangesAsync() > 0;
		}

		public async Task<int> maxUId()
		{
			return await myDbContext.User.MaxAsync(u => u.UId);
			
		}
	}
}
